//
//  TSCVCRegister2.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-12.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCVCReg2Welcome.h"
#import "TSCSDK.h"
#import "TSCVCReg2SelectRole.h"
#import "TSCVCLogin.h"

@interface TSCVCReg2Welcome ()

@end

@implementation TSCVCReg2Welcome

+ (id) vcReg2WelcomeWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_REG2_WELCOME];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    // 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:NO goBackVC:nil hasAppLogo:YES titleResourceKey:@"title_welcome" iconResourceNameArray:[NSArray arrayWithObject:@"ic_relogin_96x96.png"] iconClickedListenerArray:
            [NSArray arrayWithObject:
             // 注册事件——重新登录
             ^(UIButton * btn){
                 // 保存上次登录用户名
                 NSString * userNameOrEmail = [_ud objectForKey:UD_USER_NAME_OR_EMAIL];
                 
                 // 清空登录状态
                 //			// 注：无论clear()放在putXxx()之前还是之后，clear()总会先被调用。但commit()需要最后再调用
                 //                 [TSCMyUtil clearUD:_ud];
                 [TSCMyUtil logoutAllWithUserDefaults:_ud];
                 
                 // 将上次登录用户名再次保存至SP
                 [_ud setValue:userNameOrEmail forKey:UD_USER_NAME_OR_EMAIL]; // 注：可能为nil的要用setValue()
                 [_ud synchronize];
                 
                 // 跳转至登录界面，并关闭当前界面
                 TSCVCLogin *vcLogin = [TSCVCLogin vcLoginWithStoryboard];
                 [[self navigationController] pushViewController:vcLogin animated:YES];
                 [TSCMyUIUtil removeVCItselfAndAllPreviousVC:self];
             }]
            ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 公共方法

/**
 * 因为顾客在“选择城市”之后就提交服务器注册了，而导购在“选择店铺”之后就提交注册了，所以在两个vc中都用到这个方法。在Android中，这个方法是属于Activity的，由不同的Fragment触发；而在IOS中由于没有一个统一管理的Activity，所以暂时写在Reg2Welcome中
 *
 * @date 2015-09-16
 * @author Rio
 */
+ (void) register2_preWithVC:(TSCVCMy *)mvc ud:(NSUserDefaults *)ud userRole:(NSInteger)userRole cityId:(NSInteger)cityId shopId:(NSInteger)shopId tel:(NSString *)tel {
    // 校验提交参数
    if ([TSCMyCheckUtil checkWithString:[NSString stringWithFormat:@"%li", userRole] regexType:RegexTypeUserRole] == NO) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_select_role"];
        return;
    }
    if ([TSCMyCheckUtil checkWithString:[NSString stringWithFormat:@"%li", cityId] regexType:RegexTypeId] == NO) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_select_city"];
        return;
    }
    // 顾客
    if (userRole == DB_USER_ROLE_CUSTOMER) {
        // do nothing
    }
    // 导购
    else {
        if ([TSCMyCheckUtil checkWithString:[NSString stringWithFormat:@"%li", shopId] regexType:RegexTypeId] == NO) {
            [TSCMyUIUtil popErrWithResourceKey:@"err_select_shop"];
            return;
        }
        if ([TSCMyUtil isStringEmpty:tel] == NO && [TSCMyCheckUtil checkWithString:tel regexType:RegexTypePhone] == NO) {
            [TSCMyUIUtil popErrWithResourceKey:@"err_format_phone"];
            return;
        }
    }
    
    // 先检查网络情况，若不可用，直接返回
    if ([TSCMyNetworkUtil checkNetwork] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_network_unavailable"];
        return;
    }
    
    // 提示用户正在注册
    [mvc showDialogWithResourceKey:@"content_entering" isProcessing:YES];
    
    // 提交注册2请求
    TSCJsonUser * jsonUser = [[TSCJsonUser alloc]init];
    jsonUser.Id = [[ud objectForKey:UD_USER_ID] integerValue];
    jsonUser.loginKey = [ud objectForKey:UD_LOGIN_KEY];
    jsonUser.role = userRole;
    jsonUser.cityId = cityId;
    jsonUser.shopId = shopId;
    jsonUser.tel = tel;
    
    [self register2_S1WithVC:mvc ud:ud jsonUser:jsonUser];
}

/* private */ + (void) register2_S1WithVC:(TSCVCMy *)mvc ud:(NSUserDefaults *)ud jsonUser:(TSCJsonUser *)jsonUser {
    
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:[NSNumber numberWithLong:jsonUser.Id] forKey:@"user_id"];
    [reqDic setObject:jsonUser.loginKey forKey:@"login_key"];
    [reqDic setObject:[NSNumber numberWithLong:jsonUser.role] forKey:@"role"];
    [reqDic setObject:[NSNumber numberWithLong:jsonUser.cityId] forKey:@"city_id"];
    [reqDic setObject:[NSNumber numberWithLong:jsonUser.shopId] forKey:@"shop_id"];
    [reqDic setObject:jsonUser.tel forKey:@"tel"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_USER_REGISTER2 dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString, NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                [mvc dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                return;
            }
            case ServerRespTypeErrCode:{
                [mvc dissmisDialog];
                [TSCMyUIUtil popErrWithString:msg];
                return;
            }
            default: {
                [mvc dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                return;
            }
        }
        
        
        // 解析用户信息
        TSCJsonUser * jsonUser2 = [[TSCJsonUser alloc]init];
        // （1）Reg2相关
        jsonUser2.Id = [[contentDictionary objectForKey:@"id"] integerValue];
        jsonUser2.role = [[contentDictionary objectForKey:@"role"] integerValue];
        jsonUser2.cityId = [[contentDictionary objectForKey:@"city_id"] integerValue];
        if (jsonUser2.role == DB_USER_ROLE_GUIDE) {
            jsonUser2.shopId = [[contentDictionary objectForKey:@"shop_id"] integerValue];
            jsonUser2.shopName = [contentDictionary objectForKey:@"shop_name"];
            jsonUser2.tel = [contentDictionary objectForKey:@"tel"];
        }
        // （2）其他
        jsonUser2.emailValid = [[contentDictionary objectForKey:@"email_valid"] integerValue];
        jsonUser2.guideStatus = [[contentDictionary objectForKey:@"guide_status"] integerValue];
        jsonUser2.lastLoginTime = [[contentDictionary objectForKey:@"last_login_time"] integerValue];
        jsonUser2.picUrl = [contentDictionary objectForKey:@"user_pic_url"];
        
        // 解析导购所在店铺经营的商品分类“id、名称”列表（后续绑定BAE时设定tag使用）
        NSMutableArray * gcIdArray = [NSMutableArray array];
        NSMutableArray * tagArray = [NSMutableArray array];
        if (jsonUser2.role == DB_USER_ROLE_GUIDE) {
            NSArray * gcArray = [contentDictionary objectForKey:@"goods_class_list"];
            
            for (NSInteger i = 0, max = [gcArray count]; i < max; i++) {
                NSDictionary * gcDic = [gcArray objectAtIndex:i];
                
                [gcIdArray addObject:[gcDic objectForKey:@"id"]];
                
                [tagArray addObject:[NSString stringWithFormat:@"%@%li_%@", BAE_TAG_PREFIX_GOODS_CLASS, jsonUser2.cityId, [gcDic objectForKey:@"name"]]];
            }
        }
        
        // 将解析好的gc_id_list保存起来，后续使用
        jsonUser2.goodsClassIds = [TSCMyUtil implodeWithGlue:@"," array:gcIdArray];
        
        // 解析导购身份是否为店长
        if (jsonUser2.role == DB_USER_ROLE_GUIDE) {
            jsonUser2.guideIsManager = [[contentDictionary objectForKey:@"guide_is_manager"]intValue];
        }
        
        // 继续后续处理...
        [self register2_S2WithVC:mvc ud:ud jsonUser:jsonUser2 tagArr:tagArray];
    }];
    
}

/* private */ + (void) register2_S2WithVC:(TSCVCMy *)mvc ud:(NSUserDefaults *)ud jsonUser:(TSCJsonUser *)jsonUser tagArr:(NSArray *) tagArr {
    
    // 更新SP
    // （1）Reg2相关
    [ud setInteger:jsonUser.role forKey:UD_USER_ROLE];
    [ud setInteger:jsonUser.cityId forKey:UD_USER_CITY_ID];
    if (jsonUser.role == DB_USER_ROLE_GUIDE) {
        [ud setInteger:jsonUser.shopId forKey:UD_GUIDE_SHOP_ID];
        [ud setObject:jsonUser.shopName forKey:UD_GUIDE_SHOP_NAME];
        [ud setObject:jsonUser.tel forKey:UD_USER_TEL];
    }
    // （2）其他
    [ud setInteger:jsonUser.emailValid forKey:UD_USER_EMAIL_VALID];
    [ud setBool:YES forKey:UD_IS_NOTIFY_MSG];
    [ud setInteger:jsonUser.lastLoginTime forKey:UD_BAE_LAST_LOGIN_TIME];
    if (jsonUser.role == DB_USER_ROLE_GUIDE) {
        [ud setObject:jsonUser.goodsClassIds forKey:UD_GUIDE_GOODS_CLASS_IDS];
        [ud setInteger:jsonUser.guideIsManager forKey:UD_GUIDE_IS_MANAGER];
    }
    [ud synchronize];
    
    // 保存APP_DB
    [TSCMyDBUtil insertOrUpdateUserWithId_1:jsonUser.Id name:jsonUser.name email:jsonUser.email picUrl:jsonUser.picUrl];
    
    // 关闭dialog
    [mvc dissmisDialog];
    
    // 由系统控制后续界面该如何跳转，并关闭当前界面
    [TSCMyUIUtil dispatchLoginUIWithVC:mvc ud:ud additionalTagArray:tagArr];
    [TSCMyUIUtil removeVCItselfAndAllPreviousVC:mvc];
    
}

#pragma mark delegate

- (IBAction)gotoSelectRole:(id)sender {
    TSCVCReg2SelectRole * vcSelectRole = [TSCVCReg2SelectRole vcReg2SelectRoleWithStoryboard];
    [[self navigationController]pushViewController:vcSelectRole animated:YES];
}

@end
